﻿// This source is subject to Microsoft Public License (Ms-PL).
// Please see http://taskcardcreator.codeplex.com for details.
// All other rights reserved.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using WorkItemReportInterface;
using System.Windows.Controls;

namespace TaskCardCreator
{
  /// <summary>
  /// Interaction logic for TaskCardDetailsPopup.xaml
  /// </summary>
  public partial class ReportPropertyUserControl : UserControl, INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<IWorkItemReport> Reports { get; set; }

    public IWorkItemReport SelectedReport
    { 
      get { return selectedReport; } 
      set { selectedReport = value; OnPropertyChanged("SelectedReport"); } 
    }

    public ObservableCollection<WorkItem> WorkItems { get; set; }

    public WorkItemStore workItemStoreService;

    private IWorkItemReport selectedReport;

    private BackgroundWorker worker;

    private string pendingRequest = string.Empty;

    public ReportPropertyUserControl(IEnumerable<IWorkItemReport> reports)
    {
      DataContext = this;

      WorkItems = new ObservableCollection<WorkItem>();
      Reports = new ObservableCollection<IWorkItemReport>();

      InitializeComponent();

      foreach (var report in reports)
      {
        Reports.Add(report);
        if (SelectedReport == null)
        {
          SelectedReport = report;
        }
      }
    }

    protected void OnPropertyChanged(string name)
    {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(name));
      }
    }

    private void HyperlinkRequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
    {
      System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(e.Uri.AbsoluteUri));
      e.Handled = true;
    }

    void QueriesSelectionChanged(string queryString)
    {
      Logger.Write("Entering QueriesSelectionChanged method");

      progress.Visibility = Visibility.Visible;

      WorkItems.Clear();

      if (worker == null)
      {
        worker = new BackgroundWorker();
        worker.WorkerSupportsCancellation = false;
        worker.WorkerReportsProgress = false;

        worker.DoWork += BwDoWork;
        worker.RunWorkerCompleted += BwRunWorkerCompleted;
      }

      if (worker.IsBusy)
      {
        pendingRequest = queryString;
      }
      else
      {
        worker.RunWorkerAsync(queryString);
      }
    }

    private void BwDoWork(object sender, DoWorkEventArgs e)
    {
      Logger.Write("Entering BwDoWork method");

      var newWorkItems = new ObservableCollection<WorkItem>();

      if (!string.IsNullOrEmpty((string)e.Argument))
      {
        var q = new Query(workItemStoreService, (string)e.Argument);
        if (q.IsLinkQuery)
        {
          var queryResults = q.RunLinkQuery();
          foreach (WorkItemLinkInfo i in queryResults)
          {
            var wi = workItemStoreService.GetWorkItem(i.TargetId);
            newWorkItems.Add(wi);
          }
        }
        else
        {
          var queryResults = q.RunQuery();
          foreach (WorkItem workitem in queryResults)
          {
            newWorkItems.Add(workitem);
          }
        }
      }
      e.Result = newWorkItems;
    }

    private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      Logger.Write("Entering BwRunWorkerCompleted method");

      if (e.Cancelled == true)
      {
      }
      else if (e.Error != null)
      {
        Logger.Write(string.Format("Exception: {0}", e.Error.Message));
        MessageBox.Show(string.Format("Error: {0}", e.Error.Message));
      }
      else
      {
        var newWorkItems = (ObservableCollection<WorkItem>)e.Result;
        Logger.Write(string.Format("Work items loaded: {0}", newWorkItems.Count));
        foreach (var item in newWorkItems)
        {
          WorkItems.Add(item);
        }

        listView.SelectAll();
      }
      progress.Visibility = Visibility.Collapsed;

      // Any pending requests?
      if (pendingRequest != string.Empty)
      {
        QueriesSelectionChanged((string)pendingRequest.Clone());
        pendingRequest = string.Empty;
      }
    }
  }
}